<template>
  <!-- <div>testCount:{{ testCount }}</div> -->
  <el-select
    v-model="inputValue"
    filterable
    remote
    reserve-keyword
    :remote-method="remoteMethod"
    placeholder="Please enter a keyword"
    :loading="loading"
    style="width: 240px"
  >
    <el-option
      v-for="item in options"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    />
  </el-select>
  <div @click="toAdd">查询</div>

</template>

<script setup >


import {ref,defineEmits,watchEffect} from "vue";

// const {testCount=18} = defineProps({
//   testCount:{
//     type:Number,
//   }
// })
interface transformed {
  question:string,
  answer:string
}
const emit = defineEmits(['on-search']);

const inputValue = ref<string>("");
// const options = ref<{label:string,value:string}[]>([]);
const options = ref<{label:string,value:string}[]>([
  { label: '如何申请退款', value: '如何申请退款' },
  { label: '产品保修期多久？', value: '产品保修期多久？' },
  { label: '休息天周末安排', value: '休息天周末安排' },
])
const loading = ref(false);

const remoteMethod = (query: string) => {
  if (query) {
    loading.value = true

    setTimeout(async() => {
      console.log(query,"query")

     
      const res = await fetch('http://localhost:8000/api/questionList', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          question: query
        })
      })
      const data = await res.json()
      console.log(data,"data")
      // try {
      //     if (!data.list) {
      //       throw new Error('API 返回数据格式错误')
      //     }
      const transformedList = data.list.map((item:transformed) => ({
        label: item.question,
        value: item.question
      }))

      // 添加错误处理
      try {
        if (!Array.isArray(data.list)) {
          throw new Error('API 返回数据格式错误')
        }
        options.value = [...transformedList,{label:query,value:query}] 
        console.log(options.value, "options.value")
      } catch (error) {
        console.error('数据处理错误:', error)
        options.value = []
      }
      console.log(options.value,"options.value")
      //   } catch (error) {
      //     console.error('数据处理错误:', error)
      //     options.value = []
      //   }
      // list.value.filter((item) => {
      //   console.log(item.label.toLowerCase().includes(query.toLowerCase()),"item.label.toLowerCase().includes(query.toLowerCase())")
      //   return item.label.toLowerCase().includes(query.toLowerCase())
      // })
      loading.value = false
    }, 500)
  } 
  // else {
  //   options.value = []
  // }
}
// watchEffect(()=>{
//   console.log(inputValue.value,"更新了")
//   if(inputValue.value){
//     // emit('on-search', inputValue.value);
//   }
// })
function toAdd (){
  emit('on-search', inputValue.value);
  // count.value +=1;
}

</script>